{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import seaborn as sns\n",
    "import string\n",
    "#https://stackoverflow.com/questions/19726663/how-to-save-the-pandas-dataframe-series-data-as-a-figure\n",
    "import six\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "tbpath = '../../fits/'\n",
    "productpath = '../../postfit_derivatives/'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "rois = []\n",
    "df = pd.read_csv(tbpath + 'fit_table_reweighted.csv') #get rois in all tables (some may have failed)\n",
    "rois += list(df.roi.unique())\n",
    "\n",
    "    \n",
    "rois = list(set(rois))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "#plot side by side \n",
    "\n",
    "def simpleaxis(ax):\n",
    "    ax.spines['top'].set_visible(False)\n",
    "    ax.spines['bottom'].set_visible(False)\n",
    "    ax.spines['right'].set_visible(False)\n",
    "    ax.spines['left'].set_visible(False)\n",
    "             \n",
    "roi_us = np.sort([i for i in rois if i[:2]=='US'])#[::-1]\n",
    "# roi_other = np.sort([i for i in rois if i[:2]!='US'])#[::-1]\n",
    "roi_other = np.sort(list(pd.read_csv(productpath + \"top25.csv\").values[:,0])+['China'])\n",
    "rois = list(roi_us) + list(roi_other)\n",
    "rois.remove('US')\n",
    "# rois.remove('Gambia')\n",
    "# rois.remove('AA_Global')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "theta_ = [\"R0\",\"car (week 0)\", \"ifr (week 0)\"]\n",
    "round_ =[1,2,4,1,2,4]\n",
    "label_ = {}\n",
    "label_[\"R0\"] = \"R0\"\n",
    "label_[\"car (week 0)\"] = \"CAR (week 0)\"\n",
    "label_[\"ifr (week 0)\"] = \"IFR (week 0)\"\n",
    "label_[\"Rlast\"] = \"R current\"\n",
    "label_[\"extra_std\"] = \"Extra Variability\"\n",
    "\n",
    "def afun1(x):\n",
    "    return '%s' % float('%.1g' %x)\n",
    "\n",
    "def afun2(x):\n",
    "    return '%s' % float('%.2g' %x)\n",
    "\n",
    "df = pd.read_csv(tbpath + 'fit_table_reweighted.csv')\n",
    "dfreport = pd.DataFrame(columns=\n",
    "                        ['Region']+\n",
    "                        [\"R0 (CI)\"]+\n",
    "                        [\"ci1\"]+\n",
    "                        [\"CAR (week 0) (CI)\"]+\n",
    "                        [\"ci2\"]+\n",
    "                        [\"IFR (week 0) (CI)\"]+\n",
    "                        [\"ci3\"]+\n",
    "                        ['Rt(April 15th, 2020) (CI)']+\n",
    "                        [\"ci4\"]+\n",
    "                        ['CARt(April 15th, 2020) (CI)']+\n",
    "                        [\"ci5\"]+\n",
    "                        ['IFRt(April 15th, 2020) (CI)']+\n",
    "                        [\"ci6\"]+\n",
    "                        [\"delta weeks\"])\n",
    "\n",
    "\n",
    "\n",
    "k = -1\n",
    "for roi in rois:\n",
    "    k += 1\n",
    "    x = [roi]\n",
    "    for i in range(len(theta_)):\n",
    "        theta = theta_[i]\n",
    "#         print(roi)\n",
    "#         print(theta)\n",
    "        mu = df.loc[(df.roi==roi)&(df['quantile']=='0.5'),theta].values[0]\n",
    "        lb = df.loc[(df.roi==roi)&(df['quantile']=='0.025'),theta].values[0]\n",
    "        ub = df.loc[(df.roi==roi)&(df['quantile']=='0.975'),theta].values[0]\n",
    "        if theta == 'R0':\n",
    "            x += [afun2(mu)]+[\"(\"+afun2(lb)+\", \"+afun2(ub)+\")\"]\n",
    "        else:\n",
    "            x += [afun1(mu)]+[\"(\"+afun1(lb)+\", \"+afun1(ub)+\")\"]\n",
    "#         print(x)\n",
    "    for week in np.arange(11,0,-1):\n",
    "        theta = 'Rt (week '+str(week)+')'\n",
    "        x2 = df.loc[(df.roi==roi)&(df['quantile']=='0.5'),theta].values[0]\n",
    "        if np.isfinite(x2):\n",
    "    #             print(x2)\n",
    "            mu = df.loc[(df.roi==roi)&(df['quantile']=='0.5'),theta].values[0]\n",
    "            lb = df.loc[(df.roi==roi)&(df['quantile']=='0.025'),theta].values[0]\n",
    "            ub = df.loc[(df.roi==roi)&(df['quantile']=='0.975'),theta].values[0]\n",
    "            x += [afun2(mu)]+[\"(\"+afun1(lb)+\", \"+afun1(ub)+\")\"]\n",
    "            break\n",
    "    for week in np.arange(11,0,-1):\n",
    "        theta = 'car (week '+str(week)+')'\n",
    "        x2 = df.loc[(df.roi==roi)&(df['quantile']=='0.5'),theta].values[0]\n",
    "        if np.isfinite(x2):\n",
    "    #             print(x2)\n",
    "            mu = df.loc[(df.roi==roi)&(df['quantile']=='0.5'),theta].values[0]\n",
    "            lb = df.loc[(df.roi==roi)&(df['quantile']=='0.025'),theta].values[0]\n",
    "            ub = df.loc[(df.roi==roi)&(df['quantile']=='0.975'),theta].values[0]\n",
    "            x += [afun1(mu)]+[\"(\"+afun1(lb)+\", \"+afun1(ub)+\")\"]\n",
    "            break\n",
    "#     x += [week]\n",
    "    for week in np.arange(11,0,-1):\n",
    "        theta = 'ifr (week '+str(week)+')'\n",
    "        x2 = df.loc[(df.roi==roi)&(df['quantile']=='0.5'),theta].values[0]\n",
    "        if np.isfinite(x2):\n",
    "    #             print(x2)\n",
    "            mu = df.loc[(df.roi==roi)&(df['quantile']=='0.5'),theta].values[0]\n",
    "            lb = df.loc[(df.roi==roi)&(df['quantile']=='0.025'),theta].values[0]\n",
    "            ub = df.loc[(df.roi==roi)&(df['quantile']=='0.975'),theta].values[0]\n",
    "            x += [afun1(mu)]+[\"(\"+afun1(lb)+\", \"+afun1(ub)+\")\"]\n",
    "            break\n",
    "    x += [week]\n",
    "#     print(x)\n",
    "    try:\n",
    "        dfreport.loc[k] = x\n",
    "    except:\n",
    "        pass\n",
    "dfreport.to_csv(productpath + \"theta_UStop25_summary.csv\",sep='\\t',index=False)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# def render_mpl_table(data, col_width=3.0, row_height=0.625, font_size=14,\n",
    "#                      header_color='#40466e', row_colors=['#f1f1f2', 'w'], edge_color='w',\n",
    "#                      bbox=[0, 0, 1, 1], header_columns=0,\n",
    "#                      ax=None, **kwargs):\n",
    "#     if ax is None:\n",
    "#         size = (np.array(data.shape[::-1]) + np.array([0, 1])) * np.array([col_width, row_height])\n",
    "#         fig, ax = plt.subplots(figsize=size)\n",
    "#         ax.axis('off')\n",
    "\n",
    "#     mpl_table = ax.table(cellText=data.values, bbox=bbox, colLabels=data.columns, **kwargs)\n",
    "\n",
    "#     mpl_table.auto_set_font_size(False)\n",
    "#     mpl_table.set_fontsize(font_size)\n",
    "\n",
    "#     for k, cell in six.iteritems(mpl_table._cells):\n",
    "#         cell.set_edgecolor(edge_color)\n",
    "#         if k[0] == 0 or k[1] < header_columns:\n",
    "#             cell.set_text_props(weight='bold', color='w')\n",
    "#             cell.set_facecolor(header_color)\n",
    "#         else:\n",
    "#             cell.set_facecolor(row_colors[k[0]%len(row_colors) ])\n",
    "#     return ax\n",
    "#     render_mpl_table(dfreport, header_columns=0, col_width=8.0)\n",
    "#     plt.savefig(\"../postfit_derivatives/\"+theta+\"_summary.png\")\n",
    "#     plt.clf()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
